from dataclasses import dataclass
from injector import inject
from internal.service.cos_service import CosService
from internal.schema.upload_schema import UploadSchema, UploadImageSchema, UploadSchemaResp
from pkg.resp import success_json
from pkg.resp.response import validate_error_json


@inject
@dataclass
class UploadFileHandler:
    cos_service: CosService

    def upload_file(self):
        req = UploadSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        data = self.cos_service.upload_file(req.file.data)
        resp = UploadSchemaResp()
        return success_json(resp.dump(data))

    def upload_img(self):
        req = UploadImageSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        data = self.cos_service.upload_file(req.file.data, True)
        img_url = self.cos_service.get_img_url(data.key)
        return success_json({"img_url": img_url})
